package cn.hl.hm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hl.hm.entity.*;
import cn.hl.hm.util.*;
import cn.hl.hm.vo.DriverDetailVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hl.hm.constants.AlipayConfig;
import cn.hl.hm.constants.WeixinPayConfig;
import cn.hl.hm.dao.TBackstageOperationRecordEntityMapper;
import cn.hl.hm.dao.TRechargeActivityMapper;
import cn.hl.hm.entity.backstage.TBackstageOperationRecordEntity;
import cn.hl.hm.service.DriverService;
import cn.hl.hm.service.RechargeRecoardService;
import cn.hl.hm.util.chinapay.StringUtil;



@Controller
@RequestMapping("/rechargeController")
public class RechargeController {
	private static Logger logger = Logger.getLogger(RechargeController.class);
	private final static SimpleDateFormat hhmmSdf= new SimpleDateFormat("yyyy-MM-dd HH:mm");

	@Autowired
	RechargeRecoardService rechargeRecoardService;
	@Autowired
	DriverService driverService;
	
	@Autowired
	TBackstageOperationRecordEntityMapper tBackstageOperationRecordEntityMapper;
	
	@Autowired
	TRechargeActivityMapper tRechargeActivityMapper;
	/**
	  * @Title: getRechargeCode  
	  * @Description: 充值
	  * @date: 2017年4月6日
	  * @author:大和
	  * @param userAccount
	  * @param rechargeId
	  * @param type
	  * @param request
	  * @param response
	  * @return String 
	  * @throws
	 */
	@RequestMapping(value = "/getRechargeCode", method = RequestMethod.POST)
	public @ResponseBody String getRechargeCode(
			@RequestParam("driverId") Integer driverId, // 用户账户
			Integer rechargeId, // 充值金额Id
			@RequestParam("type") String type, // 充值渠道 1微信 2支付宝 3现金
			BigDecimal userDefinedAmount,//自定义金额
			HttpServletRequest request, HttpServletResponse response) {

		logger.info("资金---充值下单（接口1）---rechargeController/getRechargeCode");
		if(rechargeId!=null) {
			TRechargeActivity tRechargeActivity = tRechargeActivityMapper.selectByPrimaryKey(rechargeId);
			if(tRechargeActivity==null){
				logger.info("参数有误");
				Result.ok(null, InfoCode.FAILURE, response); 
				return null;
			}
		}
		if(userDefinedAmount!=null) {
			if(userDefinedAmount.compareTo(new BigDecimal(0))<=0) {
				
				logger.info("参数有误");
				Result.ok(null, InfoCode.FAILURE, response); 
				return null;
			
			}
		}
		
		
		
		
		if(type.equals("1")||type.equals("2")||type.equals("3")){
			
		}else {
			logger.info("参数有误");
			Result.ok(null, InfoCode.FAILURE, response); 
			return null;
		}
		
		
		Map<String, String> map = new HashMap<>();
		try {
			Driver param = new Driver();
			param.setId(driverId);
			List<Driver> selectDriver = driverService.selectDriver(param);
			if(selectDriver!=null&&selectDriver.size()>0){
				Driver driver = selectDriver.get(0);
				BigDecimal remainCash = driver.getRemainCash();
				if(remainCash==null){
					remainCash= new BigDecimal(0);
				}
				
				
				// 生成充值Code
				String code = OrderUtil.getInstance().getRoadFeeOrderCode();
				map.put("rechargeCode", code);
				RechargeRecoard r = new RechargeRecoard();
				r.setRechargeCode(code);
				r.setCreateTime(new Date());
				r.setStatus("1");
				r.setType(Integer.parseInt(type));
				r.setUserphone(driver.getDriverAccount());
				//新增自定义
				if(rechargeId!=null) {
					TRechargeActivity tRechargeActivity = tRechargeActivityMapper.selectByPrimaryKey(rechargeId);
					if(tRechargeActivity==null){
						logger.info("参数有误");
						Result.ok(null, InfoCode.FAILURE, response); 
						return null;
					}
					r.setAmount(tRechargeActivity.getGiftAmount().add(tRechargeActivity.getAmount()));
					r.setRechargeActivityId(rechargeId);
				}else {
					r.setAmount(userDefinedAmount);
					
				}
				
				r.setDriverId(driverId);
				
				BigDecimal amount = r.getAmount();
				if(amount==null){
					amount= new BigDecimal(0);
				}
				r.setRemainCash(remainCash.add(amount));
				r.setOperType(1);// 操作类型
				int addRechargeRecoard = rechargeRecoardService.addRechargeRecoard(r);
				if(addRechargeRecoard>0){
					
					if(type.equals("3")){
						Driver driver2 = new Driver();
						driver2.setRemainCash(r.getRemainCash());
						driver2.setId(r.getDriverId());
						
						int res = driverService.updateDriver(driver2);
							if(res>0){
								Result.ok(map, InfoCode.SUCCESS, response);
								return null;
							}else {
								Result.ok(map, InfoCode.FAILURE, response);
								return null;
							}
					}
					
					Result.ok(map, InfoCode.SUCCESS, response);
					return null;
				}else {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					return null;
				}
			}else {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			Result.ok(null, InfoCode.FAILURE, response); 
		}
		return null;
	}
	
	
	
	/**
	* @Title: rchargeRules
	* @Description:获取充值规则
	* @author : 大和
	* @date :2016年10月12日
	* @param request
	* @param response
	* @return String
	* @throws
	 */
	@RequestMapping(value = "/rchargeRules", method = RequestMethod.POST)
	public @ResponseBody String rchargeRules(String viewStatus,
			HttpServletRequest request, HttpServletResponse response) {
		logger.info("【查询充值返现活动列表】 ：start"  );
		logger.info("资金/资金---充值列表/充值规则排序更改---rechargeController/rchargeRules");
		try {
			TRechargeActivity  param = new TRechargeActivity();
			param.setEffective("1");//有效的
			if(StringUtil.isEmpty(viewStatus)){
				param.setViewStatus("1");//有效的
			}
			List<TRechargeActivity> result = tRechargeActivityMapper.selectByConditions(param);
			Result.ok(result, InfoCode.SUCCESS, response); 
			return null;

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			Result.ok(null, InfoCode.FAILURE, response); 
		}
		return null;
	}
	

	
	 
	
	@RequestMapping(value = "/addRechargeActivtiy", method = RequestMethod.POST)
	@ResponseBody
	public String addOrderRule(@RequestParam("amount") BigDecimal amount,
			@RequestParam("giftAmount") BigDecimal giftAmount, 
			HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("增加充值规则");
		try {
			TRechargeActivity record = new TRechargeActivity();
			record.setAmount(amount);
			record.setGiftAmount(giftAmount);
			record.setEffective("1");
			tRechargeActivityMapper.insertSelective(record);
			Result.ok(null, InfoCode.SUCCESS, response); 
		}catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			Result.ok(null, InfoCode.FAILURE, response); 
		}
		return null;
	}
	@RequestMapping(value = "/updateRechargeActivtiy", method = RequestMethod.POST)
	@ResponseBody
	public String updateRechargeActivtiy(@RequestParam("amount") BigDecimal amount,
			@RequestParam("giftAmount") BigDecimal giftAmount, 
			@RequestParam("id") Integer id,
			HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("修改充值规则");
		try {
			TRechargeActivity record = new TRechargeActivity();
			//int sortOld =record.getSortNum();
			TRechargeActivity tRechargeActivity = tRechargeActivityMapper.selectByPrimaryKey(id);
			record.setId(id);
			//record.setAmount(amount);
			//record.setGiftAmount(giftAmount);
			record.setEffective("0");
			record.setSortNum(0);
			int updateByPrimaryKeySelective = tRechargeActivityMapper.updateByPrimaryKeySelective(record);
			
			if(updateByPrimaryKeySelective>0){
				TRechargeActivity record2 = new TRechargeActivity();
				record2.setAmount(amount);
				record2.setGiftAmount(giftAmount);
				record2.setEffective("1");
				record2.setSortNum(tRechargeActivity.getSortNum());
				
				tRechargeActivityMapper.insertSelective(record2);
			}else {
				Result.ok(null, InfoCode.FAILURE, response); 
			}
			
			Result.ok(null, InfoCode.SUCCESS, response); 
		}catch (Exception e) {
			e.printStackTrace();
			logger.error(e); 
			Result.ok(null, InfoCode.FAILURE, response); 
		}
		return null;
	}
	@RequestMapping(value = "/delRechargeActivtiy", method = RequestMethod.POST)
	@ResponseBody
	public String delRechargeActivtiy(
			@RequestParam("id") Integer id,
			HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("删除充值规则");
		try {
			TRechargeActivity record = new TRechargeActivity();
			record.setId(id);
			//record.setAmount(amount);
			//record.setGiftAmount(giftAmount);
			record.setEffective("0");
			record.setSortNum(0);
			int updateByPrimaryKeySelective = tRechargeActivityMapper.updateByPrimaryKeySelective(record);
			
			if(updateByPrimaryKeySelective>0){
				Result.ok(null, InfoCode.SUCCESS, response); 
				return null;
			}else{
				Result.ok(null, InfoCode.FAILURE, response); 
				return null;
			}
				
			
		}catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			Result.ok(null, InfoCode.FAILURE, response); 
		}
		return null;
	}
	
	@RequestMapping(value = "/updateSortNum", method = RequestMethod.POST)
	@ResponseBody
	public String updateSortNum(
//			@RequestParam("id") Integer id,
//			@RequestParam("sortNum") Integer sortNum,
			TRechargeActivity  param,
			HttpServletRequest request,
			HttpServletResponse response) {
		try {
			
	 
			List<TRechargeActivity> result = tRechargeActivityMapper.selectByConditions(param);
			if(result!=null && result.size()>0) {
				Result.ok(null, InfoCode.SORTNUM_ERROR, response); 
				return null;
			}else {
				int updateByPrimaryKeySelective = tRechargeActivityMapper.updateByPrimaryKeySelective(param);
				
				if(updateByPrimaryKeySelective>0){
					Result.ok(null, InfoCode.SUCCESS, response); 
					return null;
				}else{
					Result.ok(null, InfoCode.FAILURE, response); 
					return null;
				}
			}
			
			
		}catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			Result.ok(null, InfoCode.FAILURE, response); 
		}
		return null;
	}
	
	/**
	 * 退款记录查询
	 * @param withdrawApply
	 * @param request
	 * @param response
	 * @return 山治
	 * @throws IOException
	 */
	@RequestMapping(value = "/selectWithdrawApply", method = RequestMethod.POST)
	public String selectWithdrawApply( RechargeRecoard rechargeRecoard,
			@RequestParam Integer driverId,
			@RequestParam Integer operType,
			@RequestParam Integer pageCount,
			@RequestParam Integer pageId,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("退款记录---withdrawApplyController/selectWithdrawApply");
		request.setCharacterEncoding("UTF-8");
		try {
			List<RechargeRecoard> selectRechargeRecoard = rechargeRecoardService.selectRechargeRecoard(rechargeRecoard);
			rechargeRecoard.setPageId(null);
			rechargeRecoard.setPageCount(null);
			int num =rechargeRecoardService.selectRechargeRecoardNum(rechargeRecoard);
			Map map =AppPager.getPageInfo(selectRechargeRecoard, pageCount, num,pageId);
			Result.ok(map, InfoCode.SUCCESS, response);
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}
	/**
	 * 保全金收费列表
	 * @param pageId
	 * @param rechargeRecoard
	 * @param pageCount
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/selectSecurityList", method = RequestMethod.POST)
	public String selectSecurityList(@RequestParam Integer pageId, RechargeRecoard rechargeRecoard, @RequestParam Integer pageCount,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("保全金收费列表接口---rechargeController/selectSecurityList");
		request.setCharacterEncoding("UTF-8");
		try {
			if (StringUtils.isNotBlank(rechargeRecoard.getBeString())
					&& StringUtils.isNotBlank(rechargeRecoard.getEndString())) {
				if (rechargeRecoard.getBeString().trim().equals("''")) {

				} else if (rechargeRecoard.getEndString().trim().equals("''")) {

				} else if (rechargeRecoard.getBeString().trim().equals("\"\"")) {

				} else if (rechargeRecoard.getEndString().trim().equals("\"\"")) {

				} else {
					rechargeRecoard.setBeString(rechargeRecoard.getBeString().trim() + " 00:00:00");
					rechargeRecoard.setEndString(rechargeRecoard.getEndString().trim() + " 23:59:59");
				}
			}

			AppPager handle = AppPager.handle(pageId, pageCount);
			rechargeRecoard.setPageId(handle.getPageId());
			rechargeRecoard.setPageCount(handle.getPageCount());
			List<RechargeRecoard> rechargeRecoardList = rechargeRecoardService.selectSecurityList(rechargeRecoard);
			
			rechargeRecoard.setPageId(null);
			rechargeRecoard.setPageCount(null);
			
			int num=rechargeRecoardService.selectSecurityListNum(rechargeRecoard);
			BigDecimal allAmount=rechargeRecoardService.selectSumAmount(rechargeRecoard);
			Map map = AppPager.getPageInfo(rechargeRecoardList, pageCount, num,pageId);
			map.put("allAmount", allAmount);
			Result.ok(map, InfoCode.SUCCESS, response);
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			
		}
		return null;
	}

	/**
	 * 保全金收费列表
	 * @param pageId
	 * @param rechargeRecoard
	 * @param pageCount
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/selectSecurityAndRoadFeeList", method = RequestMethod.POST)
	public String selectSecurityAndRoadFeeList(@RequestParam Integer pageId, RechargeRecoard rechargeRecoard, @RequestParam Integer pageCount,
									 HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("配载费保全金消费列表接口---rechargeController/selectSecurityAndRoadFeeList");
		request.setCharacterEncoding("UTF-8");
		try {
			Map map = rechargeRecoardService.getSecurityAndRoadFeeMap(pageId, pageCount,rechargeRecoard);
			Result.ok(map, InfoCode.SUCCESS, response);
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);

		}
		return null;
	}

	@RequestMapping(value = "/exportSecurityAndRoadFeeList", method = RequestMethod.GET)
	public void exportSecurityAndRoadFeeList(@RequestParam(value = "pageId",required = false,defaultValue = "0") Integer pageId,
											 @RequestParam(value = "pageCount",required = false,defaultValue = "1048576") Integer pageCount,
											 RechargeRecoard rechargeRecoard,
											   HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("配载费保全金消费数据导出接口---rechargeController/exportSecurityAndRoadFeeList");
		request.setCharacterEncoding("UTF-8");
		try {
			String ctxPath = request.getSession().getServletContext().getRealPath("/") + "export/";
			String fileName = "";
			File file = new File(ctxPath.toString());

			if (!file.exists()) {
				file.mkdir();
				try {
					Thread.sleep(1500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			Map<String,Object> map = rechargeRecoardService.getSecurityAndRoadFeeMap(pageId, pageCount,rechargeRecoard);
			fileName=System.currentTimeMillis()+".xls";
			ExportData.exportSecurityAndRoadFeeListExcel(ctxPath + fileName,map);

			FileInputStream input=new FileInputStream(ctxPath + fileName);
			OutputStream output=response.getOutputStream();
			response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
			byte[] b=new byte[1024*1024];
			int len=0;
			while((len=input.read(b))!=-1){
				output.write(b,0,len);
			}
			input.close();
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
 * 系统修改司机的钱
 * @param phone
 * @param type
 * @param changeMoney
 * @param request
 * @param response
 * @return
 * @throws IOException
 */
	@RequestMapping(value = "/systemMakeRemainCash", method = RequestMethod.POST)
	public String systemMakeRemainCash(
			@RequestParam String phone, 
			@RequestParam String type,
			@RequestParam String changeMoney,
			@RequestParam Integer userId,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("系统修改司机的钱---rechargeController/systemMakeRemainCash");
		request.setCharacterEncoding("UTF-8");
		try {
			Driver driver =new Driver();
			driver.setDriverAccount(phone);
			driver.setDriverStatus("3");
			List<Driver> selectDriver = driverService.selectDriver(driver);
			if(selectDriver!=null&&selectDriver.size()==1) {
				BigDecimal remain=selectDriver.get(0).getRemainCash();
				BigDecimal changemoney=new BigDecimal(changeMoney);
				String str="";
				if(type.equals("10")) {
					str="增加";
					remain=remain.add(changemoney);
					
				}else if(type.equals("20")) {
					remain=remain.subtract(changemoney);
					if(remain.compareTo(new BigDecimal(0))==-1) {
						Result.ok(null, InfoCode.DRIVER_REMAIN_ERROR, response);
						return null;
					}
					str="减少";
				}
				int driverId = selectDriver.get(0).getId();
				driver.setId(driverId);
				driver.setRemainCash(remain);
				driverService.updateDriver(driver);
				RechargeRecoard rechargeRecoard=new RechargeRecoard();
				rechargeRecoard.setOperType(Integer.parseInt(type));
				rechargeRecoard.setDriverId(driverId);
				rechargeRecoard.setUserphone(phone);
				rechargeRecoard.setAmount(changemoney);
				rechargeRecoard.setRemainCash(remain);
				rechargeRecoard.setStatus("2");
				rechargeRecoard.setReceiptsStatus("0");
				rechargeRecoard.setPaycashStatus("0");
				rechargeRecoard.setCreateTime(new Date());
				
				rechargeRecoardService.addRechargeRecoard(rechargeRecoard);
				TBackstageOperationRecordEntity backstageOperationRecordEntity=new TBackstageOperationRecordEntity();
				backstageOperationRecordEntity.setCreateTime(new Date());
				backstageOperationRecordEntity.setOperationContent("对司机账户"+phone+"进行余额"+str+changeMoney+"当前余额为"+remain);
				backstageOperationRecordEntity.setPhone(phone);
				backstageOperationRecordEntity.setUserId(userId);
				tBackstageOperationRecordEntityMapper.insertSelective(backstageOperationRecordEntity);
			}else {
				Result.ok(null, InfoCode.DRIVER_EXIXTS_ERROR, response);
				return null;
			}
			Result.ok(null, InfoCode.SUCCESS, response);
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			
		}
		return null;
	}
	
}
